package main

import (
	"ReferenceMonitor/sdk/framework"
	"ReferenceMonitor/sdk/rpc/service_manager"
	"bufio"
	"flag"
	"fmt"
	"log"
	"os"
	"strings"
)

var dms *framework.DMServiceAPI

const TEST_IP = "127.0.0.1"

func printUsage() {
	help := `Commands:
`
	fmt.Print(help)
}

func runCli() {
	stdReader := bufio.NewReader(os.Stdin)
	for {
		line, err := stdReader.ReadString('\n')
		if err != nil {
			fmt.Println("Failed to read commands", err)
			return
		}
		line = strings.Trim(line, " \r\n")
		params := strings.Split(line, " ")
		cmd := params[0]
		//fmt.Println("read commends", cmd, params)
		res := false
		switch cmd {
		case "conn":
			fmt.Println("try to connect", params[1])
			res = dms.ConnectDevice(params[1])
		case "code":
			fmt.Println("enter device code", params[1])
			res = dms.VerifyDevice(params[1])
		case "gallery":
			fmt.Println("launch gallery")

		case "q":
			fmt.Println("Exit")
			return
		}
		if !res {
			fmt.Println("Operation Failed!")
		}
	}
}

func mockClient() {
	ip := TEST_IP
	code := "12345"
	if !dms.ConnectDevice(ip) {
		fmt.Println("ConnectDevice: Failed ", ip)
		return
	}
	if !dms.VerifyDevice(code) {
		fmt.Println("VerifyDevice: Failed ", code)
		return
	}
}

func main() {
	var IP, TY string
	flag.Parse()
	if flag.NArg() < 2 {
		fmt.Println("Usage: server ip type[tv|phone]")
		return
	}
	IP = flag.Arg(0)
	TY = flag.Arg(1)
	if TY != service_manager.DEVICE_TV &&
		TY != service_manager.DEVICE_PHONE {
		fmt.Println("Invalid device type [tv|phone]: ", TY)
		return
	}

	//flag.StringVar(&TY)
	//flag.StringVar(&IP, "ip", "127.0.0.1", "set ip addr")
	//flag.Parse()
	log.Printf("Device:%s Start Reference Monitor At:%s\n", TY, IP)
	dms = framework.NewDMSApi()
	dms.Start(IP, TY)
	defer dms.StopService()
	printUsage()
	if IP == TEST_IP {
		runCli()
	} else {
		mockClient()
	}
}
